package picturesender;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;

/**
 * @author sad
 */
public class SendPacket {

    private final int command;
    private final ByteArrayOutputStream stream;
    private static final byte[] endMarker = ByteBuffer.allocate(4).putInt(0xFAAFABBA).array();

    public SendPacket(int command) {
        this.command = command;
        stream=new ByteArrayOutputStream(200);
    }

    public SendPacket putShort(short value) throws IOException {
        stream.write((value>>8)&0xFF);
        stream.write(value&0xFF);
        return this;
    }
    
    public SendPacket putString(String value) throws IOException {
        byte[]buffer=value.getBytes("UTF-8");
        writeShortToStream(stream, (short) buffer.length);
        putByteBuffer(buffer);
        return this;
    }

    public SendPacket putInt(int value) throws IOException {
        writeIntToStream(stream, value);
        return this;
    }
    
    private void writeIntToStream(OutputStream stream, int value) throws IOException{
        stream.write((value>>24)&0xFF);
        stream.write((value>>16)&0xFF);
        stream.write((value>>8)&0xFF);
        stream.write(value&0xFF);
    }
    
    private void writeShortToStream(OutputStream stream, short value) throws IOException{
        stream.write((value>>8)&0xFF);
        stream.write(value&0xFF);
    }

    public SendPacket putByteBuffer(byte[] value) throws IOException {
        stream.write(value);
        return this;
    }

    public SendPacket putByte(byte value) throws IOException {
        stream.write((int) value);
        return this;
    }

    public void send(OutputStream stream) throws IOException {
        writeIntToStream(stream, this.stream.size()+1+4);
        stream.write(command);
        this.stream.writeTo(stream);
        stream.write(endMarker);
    }
    
    public void sendAndFlush(OutputStream stream) throws IOException{
        send(stream);
        stream.flush();
    }
}
